package api

import (
	"FeedXmh/app/dao"
	"fmt"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/encoding/gjson"
	"github.com/gogf/gf/encoding/gparser"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/util/gconv"
	"paco_toolkit/common"
)

var Mini_program = mini_program{}

type mini_program struct{}

func (*mini_program) Jscode2session(r *ghttp.Request) {
	str := ""
	params := r.GetMap()
	params["appid"] = g.Cfg().GetString("wechat.AppID")
	params["secret"] = g.Cfg().GetString("wechat.AppSecret")
	if res, err := g.Client().Get("https://api.weixin.qq.com/sns/jscode2session", params); err != nil {
		g.Log().Line().Error(err)
	} else {
		str = res.ReadAllString()
		g.Log().Line(true).Debug(str)
		type Model struct {
			//session_key string
			Openid string `json:"openid"`
		}
		m := Model{}
		err := gjson.DecodeTo(str, &m)
		if err != nil {
			g.Log().Line(true).Error(err)
		} else {
			str, err = gparser.VarToJsonString(m)
			if err != nil {
				g.Log().Line(true).Error(err)
			} else {
				g.Log().Line(true).Debug(str)
			}
		}
	}
	r.Response.Write(str)
	r.ExitAll()
}

func (*mini_program) CityLookup(r *ghttp.Request) {
	str := ""
	params := r.GetQueryMap()
	if res, err := g.Client().Get("https://geoapi.qweather.com/v2/city/lookup", params); err != nil {
		g.Log().Line().Error(err)
	} else {
		str = res.ReadAllString()
		g.Log().Line().Info(str)
	}
	r.Response.Write(str)
	r.ExitAll()
}

func (*mini_program) WeatherNow(r *ghttp.Request) {
	str := ""
	params := r.GetQueryMap()
	if res, err := g.Client().Get("https://devapi.qweather.com/v7/weather/now", params); err != nil {
		g.Log().Line().Error(err)
	} else {
		str = res.ReadAllString()
		g.Log().Line().Info(str)
	}
	r.Response.Write(str)
	r.ExitAll()
}

func (*mini_program) Weather24h(r *ghttp.Request) {
	str := ""
	params := r.GetQueryMap()
	if res, err := g.Client().Get("https://devapi.qweather.com/v7/weather/24h", params); err != nil {
		g.Log().Line().Error(err)
	} else {
		str = res.ReadAllString()
		g.Log().Line().Info(str)
	}
	r.Response.Write(str)
	r.ExitAll()
}

func (*mini_program) Weather7d(r *ghttp.Request) {
	str := ""
	params := r.GetQueryMap()
	if res, err := g.Client().Get("https://devapi.qweather.com/v7/weather/7d", params); err != nil {
		g.Log().Line().Error(err)
	} else {
		str = res.ReadAllString()
		g.Log().Line().Info(str)
	}
	r.Response.Write(str)
	r.ExitAll()
}

func (*mini_program) GetUser(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	wx_openid := gconv.String(params["openid"])

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	model := db.Model("v_user")
	model = model.Where("wx_openid=?", wx_openid)
	record, err := model.One()
	if err != nil {
		res["code"] = -1
		res["msg"] = err.Error()
	} else {
		if record != nil {
			res["data"] = record.Map()
		} else {
			res["code"] = -1
			res["msg"] = "not found"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*mini_program) Login(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()
	wx_openid := gconv.String(params["openid"])
	userid := gconv.String(params["userid"])
	pwd := gconv.String(params["pwd"])

	db := g.DB(g.Cfg().GetString("custom.db_name"))

	result, err := db.Model("t_user").Where(fmt.Sprintf(" userid='%s' and pwd='%s' ", userid, pwd)).All()
	if err != nil {
		g.Log().Line().Error(err)
		res["code"] = -1
		res["msg"] = err.Error()
	} else {
		list := result.List()
		if len(list) > 0 {
			//账号密码正确,删除已经存在的openid

			result, err := db.Model("t_user").Where(fmt.Sprintf(" wx_openid='%s' ", wx_openid)).All()
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				list := result.List()
				if len(list) > 0 {
					//删除旧
					item := list[0]
					item["wx_openid"] = nil
					db.Model("t_user").Data(item).Save()
				}
			}

			item := list[0]
			item["wx_openid"] = wx_openid
			_, err1 := db.Model("t_user").Data(item).Save()
			if err1 != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["code"] = 0
				//res["data"]=item
			}
		} else {
			//失败
			res["code"] = -1
			res["msg"] = "错误账号/密码"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*mini_program) ChangePwd(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()
	wx_openid := gconv.String(params["openid"])
	userid := gconv.String(params["userid"])
	pwd := gconv.String(params["pwd"])
	pwd1 := gconv.String(params["pwd1"])
	if pwd == pwd1 {
		db := g.DB(g.Cfg().GetString("custom.db_name"))

		count, err := db.GetCount("SELECT * FROM t_user WHERE wx_openid='" + wx_openid + "' and userid='" + userid + "'")
		if err == nil && count > 0 {
			sqlres, _ := db.Model("t_user").Data(gdb.Map{"pwd": pwd}).Where("wx_openid=? and userid=?", wx_openid, userid).Update()
			if a, err := sqlres.RowsAffected(); err == nil && a >= 0 {
				res["code"] = 0
				res["msg"] = "修改成功"
			} else {
				res["code"] = -1
				res["msg"] = "修改失败"
			}
		} else {
			res["code"] = -1
			res["msg"] = "其他错误"
		}
	} else {
		res["code"] = -1
		res["msg"] = "两次密码不一致"
	}

	r.Response.WriteJson(res)
	r.ExitAll()

}

func (*mini_program) Logout(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()
	wx_openid := gconv.String(params["openid"])

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	result, err := db.Model("t_user").Where(fmt.Sprintf(" wx_openid='%s' ", wx_openid)).All()
	if err != nil {
		g.Log().Line().Error(err)
		res["code"] = -1
		res["msg"] = err.Error()
	} else {
		list := result.List()
		if len(list) > 0 {
			//登录成功，更新wx_openid
			item := list[0]
			item["wx_openid"] = nil
			_, err1 := db.Model("t_user").Data(item).Save()
			if err1 != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {

			}
		} else {
			//失败
			res["code"] = -1
			res["msg"] = "错误openid"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (*mini_program) SetDefaultFarm(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetFormMap()
	wx_openid := gconv.String(params["openid"])
	default_farm := gconv.Int(params["default_farm"])

	db := g.DB(g.Cfg().GetString("custom.db_name"))
	result, err := db.Model("t_user").Where(fmt.Sprintf(" wx_openid='%s' ", wx_openid)).All()
	if err != nil {
		g.Log().Line().Error(err)
		res["code"] = -1
		res["msg"] = err.Error()
	} else {
		list := result.List()
		if len(list) > 0 {
			//登录成功，更新wx_openid
			item := list[0]
			if default_farm > 0 {
				item["default_farm"] = default_farm
			} else {
				item["default_farm"] = nil
			}

			_, err1 := db.Model("t_user").Data(item).Save()
			if err1 != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {

			}
		} else {
			//失败
			res["code"] = -1
			res["msg"] = "错误openid"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FarmList(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		if dao.CheckApiPermission("/Api/Farm/List", r.Method, userid) {
			farm_list := dao.GetPermisFarm(userid)
			res["data"] = farm_list
			res["count"] = len(farm_list)
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}

		r.Response.WriteJson(res)
		r.ExitAll()
	}

}

func (a *mini_program) HouseList(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	farmid := gconv.String(params["farmid"])

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/House", r.Method, userid) {
			model := db.Model("t_house")
			if id != "" {
				model.Where(" id=? ", id)
			}
			if farmid != "" {
				model.Where(" farmid=? ", farmid)
			}

			r, err := model.All()
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				list := r.List()
				res["data"] = list
				res["count"] = len(list)
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FeedNodeSimple(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	//device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	/*if device_type != "" {
		where += " and device_type='" + device_type+"'"
	}*/
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		if dao.CheckApiPermission("/Api/Device/Feednode/Simple", r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {

			} else {
				where += fmt.Sprintf(" and houseid in (SELECT houseid FROM t_user_house WHERE userid='%s')", userid)
			}
			db := g.DB(g.Cfg().GetString("custom.db_name"))
			model := db.Model("v_hzgw_node").Fields("mode,alarm,alarm_ext,online,son")
			records, err := model.Where(where).All()
			if err != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				res["code"] = 0
				res["data"] = list
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FeedNode(r *ghttp.Request) {
	res := g.Map{
		"code": 0,
		"msg":  "",
		"data": nil,
	}

	params := r.GetQueryMap()

	order := r.GetString("order")

	id := gconv.String(params["id"])
	houseid := gconv.String(params["houseid"])
	farmid := gconv.String(params["farmid"])
	hnum_prefix := gconv.String(params["hnum_prefix"])
	key := gconv.String(params["key"])
	//device_addr := gconv.String(params["device_addr"])
	//device_type := gconv.String(params["device_type"])
	addr := gconv.String(params["addr"])
	sn := gconv.String(params["sn"])

	where := " 1=1 "
	if id != "" {
		where += " and id=" + id
	}
	if houseid != "" {
		where += " and houseid=" + houseid
	}
	if farmid != "" {
		where += " and farmid=" + farmid
	}
	if hnum_prefix != "" {
		where += " and hnum LIKE '" + hnum_prefix + "%' "
	}
	if addr != "" {
		where += fmt.Sprintf(" and addr='%s'", addr)
	}
	if sn != "" {
		where += fmt.Sprintf(" and sn='%s'", sn)
	}
	/*if device_type != "" {
		where += " and device_type='" + device_type+"'"
	}*/
	if key != "" {
		where += " and CONCAT(addr,sn,hnum) LIKE '%" + key + "%'"
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		if dao.CheckApiPermission("/Api/Device/Feednode", r.Method, userid) {
			//管理员可以看到全部，其他角色按照权限获取
			if dao.IsAdmin(userid) || dao.IsService(userid) {

			} else {
				where += fmt.Sprintf(" and houseid in (SELECT houseid FROM t_user_house WHERE userid='%s')", userid)
			}
			db := g.DB(g.Cfg().GetString("custom.db_name"))
			model := db.Model("v_hzgw_node")
			if order != "" {
				model = model.Order(order)
			}
			records, err := model.Where(where).All()
			if err != nil {
				g.Log().Line().Error(err)
				res["msg"] = err.Error()
				res["code"] = -1
			} else {
				list := records.List()
				res["code"] = 0
				res["data"] = list
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FarmSumMode(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/Farm/SumMode", r.Method, userid) {

			data := g.List{}
			for i := 0; i < 7; i++ {
				sql := ""
				if id != "" {
					sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE farmid=%s) AND `mode`=%d;", id, i)
				} else {
					if dao.IsAdmin(userid) || dao.IsService(userid) {
						sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE `mode`=%d;", i)
					} else {
						sql = fmt.Sprintf("SELECT count(1) AS num FROM t_hzfgw_node_para WHERE addr in (SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s')) AND `mode`=%d;", userid, i)
					}
				}
				record, err := db.GetOne(sql)
				if err != nil {
					g.Log().Line().Error(err)
					//res["code"]=-1
					//res["msg"] = err.Error()
					//break
				} else {
					if record != nil {
						item := record.Map()
						item["mode"] = i
						data = append(data, item)
					}
				}
			}

			res["code"] = 0
			res["data"] = data
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
		r.Response.WriteJson(res)
		r.ExitAll()
	}

}

func (a *mini_program) FarmSumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/Farm/SumFeed", r.Method, userid) {
			data := g.Map{}
			begin := gtime.Now().Format("Y-m-01")
			today := gtime.Now().Format(common.DATE_FORMAT)
			sql := ""
			if id != "" {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s AND device_type='HZFGW') AND  his_date>='%s' AND his_date<='%s'; ", id, begin, today)
			} else {
				if dao.IsAdmin(userid) || dao.IsService(userid) {
					sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE  his_date>='%s' AND his_date<='%s'; ", begin, today)
				} else {
					sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS month_use_feed_auto,sum(day_use_feed_man) AS month_use_feed_man,sum(day_use_water_auto) AS month_use_water_auto,sum(day_use_water_man) AS month_use_water_man FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') AND device_type='HZFGW')  AND  his_date>='%s' AND his_date<='%s'; ", userid, begin, today)
				}
			}

			dt, err := db.GetOne(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				data["month"] = dt.Map()
			}

			today = gtime.Now().Format(common.DATE_FORMAT)
			//sql=fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s AND device_type='HZFGW') AND his_date='%s' ",id,today)

			if id != "" {
				sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s AND device_type='HZFGW') AND his_date='%s' ", id, today)
			} else {
				if dao.IsAdmin(userid) || dao.IsService(userid) {
					sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE  his_date='%s' ", today)
				} else {
					sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') AND device_type='HZFGW') AND his_date='%s' ", userid, today)
				}
			}
			dt, err = db.GetOne(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				data["day"] = dt.Map()
			}

			res["data"] = data
			res["count"] = 1
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FarmDaySumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/Farm/DaySumFeed", r.Method, userid) {
			sql := ""
			if id != "" {
				sql = " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
					fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s AND device_type='HZFGW') ", id) + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			} else {

				if dao.IsAdmin(userid) || dao.IsService(userid) {
					sql = " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
						" FROM t_hzfgw_node_status_his where 1=1 " + where +
						" GROUP BY his_date ORDER BY his_date asc;"
				} else {
					sql = " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
						fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') AND device_type='HZFGW') ", userid) + where +
						" GROUP BY his_date ORDER BY his_date asc;"
				}
			}
			dt, err := db.GetAll(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["data"] = dt.List()
				res["count"] = dt.Len()
			}

		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) FarmDayAvgFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/Farm/DayAvgFeed", r.Method, userid) {
			sql := ""
			if id != "" {
				sql = " SELECT avg(day_use_feed_auto) AS day_use_feed_auto,avg(day_use_feed_man) AS day_use_feed_man,avg(day_use_water_auto) AS day_use_water_auto,avg(day_use_water_man) AS day_use_water_man ,his_date " +
					fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid=%s AND device_type='HZFGW') and mode!=0 ", id) + where +
					" GROUP BY his_date ORDER BY his_date asc;"
			} else {
				if dao.IsAdmin(userid) || dao.IsService(userid) {
					sql = " SELECT avg(day_use_feed_auto) AS day_use_feed_auto,avg(day_use_feed_man) AS day_use_feed_man,avg(day_use_water_auto) AS day_use_water_auto,avg(day_use_water_man) AS day_use_water_man ,his_date " +
						" FROM t_hzfgw_node_status_his where 1=1 and mode!=0 " + where +
						" GROUP BY his_date ORDER BY his_date asc;"
				} else {
					sql = " SELECT avg(day_use_feed_auto) AS day_use_feed_auto,avg(day_use_feed_man) AS day_use_feed_man,avg(day_use_water_auto) AS day_use_water_auto,avg(day_use_water_man) AS day_use_water_man ,his_date " +
						fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM v_device WHERE farmid in (SELECT farmid FROM t_user_farm WHERE userid='%s') AND device_type='HZFGW') and mode!=0 ", userid) + where +
						" GROUP BY his_date ORDER BY his_date asc;"
				}
			}

			dt, err := db.GetAll(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["data"] = dt.List()
				res["count"] = dt.Len()
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) HouseDaySumFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/House/DaySumFeed", r.Method, userid) {
			sql := " SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date " +
				fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s AND device_type='HZFGW') ", id) + where +
				" GROUP BY his_date ORDER BY his_date asc;"
			dt, err := db.GetAll(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["data"] = dt.List()
				res["count"] = dt.Len()
			}

		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) HouseDayAvgFeed(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()
	id := gconv.String(params["id"])
	begin := gconv.String(params["begin"])
	end := gconv.String(params["end"])
	where := ""

	if begin != "" {
		where += fmt.Sprintf(" and his_date>='%s'", begin)
	}
	if end != "" {
		where += fmt.Sprintf(" and his_date<='%s'", end)
	}

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/House/DayAvgFeed", r.Method, userid) {
			sql := " SELECT avg(day_use_feed_auto) AS day_use_feed_auto,avg(day_use_feed_man) AS day_use_feed_man,avg(day_use_water_auto) AS day_use_water_auto,avg(day_use_water_man) AS day_use_water_man ,his_date " +
				fmt.Sprintf(" FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s AND device_type='HZFGW') and mode!=0 ", id) + where +
				" GROUP BY his_date ORDER BY his_date asc;"
			dt, err := db.GetAll(sql)
			if err != nil {
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				res["data"] = dt.List()
				res["count"] = dt.Len()
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}

func (a *mini_program) GetHouseWithDetail(r *ghttp.Request) {
	res := g.Map{
		"code":  0,
		"msg":   "",
		"data":  nil,
		"count": 0,
	}
	params := r.GetQueryMap()

	id := gconv.String(params["id"])
	farmid := gconv.String(params["farmid"])
	key := gconv.String(params["key"])

	openid := gconv.String(params["openid"])
	userid, err := dao.GetUserIdByOpenID(openid)
	if err != nil {
		res["msg"] = err.Error()
		res["code"] = -1
	} else {
		db := g.DB(g.Cfg().GetString("custom.db_name"))
		if dao.CheckApiPermission("/Api/House/Detail", r.Method, userid) {
			model := db.Model("t_house")
			if id != "" {
				model.Where(" id=? ", id)
			}
			if farmid != "" {
				model.Where(" farmid=? ", farmid)
			}
			if key != "" {
				model.Where(" housename like '%?%'", key)
			}

			r, err := model.All()
			if err != nil {
				g.Log().Line().Error(err)
				res["code"] = -1
				res["msg"] = err.Error()
			} else {
				list := r.List()
				for k, v := range list {
					housid := gconv.String(v["id"])

					sql := " SELECT d.houseid,count(s.online=1 or null) as onlineNum,count(1) as deviceNum,COUNT(s.alarm>0 or s.`online`=0 or null) as alarmNum FROM v_device d " +
						" inner JOIN t_hzfgw_node_status s on d.device_addr = s.addr " +
						fmt.Sprintf(" WHERE d.houseid = %s GROUP BY d.houseid", housid)
					dt, err := db.GetOne(sql)
					if err != nil {
						g.Log().Line().Error(err)
					} else {
						if dt != nil {
							list[k]["onlineNum"] = dt.Map()["onlineNum"]
							list[k]["deviceNum"] = dt.Map()["deviceNum"]
							list[k]["alarmNum"] = dt.Map()["alarmNum"]
						} else {
							list[k]["onlineNum"] = 0
							list[k]["deviceNum"] = 0
							list[k]["alarmNum"] = 0
						}

					}

					today := gtime.Now().Format(common.DATE_FORMAT)
					sql = fmt.Sprintf("SELECT sum(day_use_feed_auto) AS day_use_feed_auto,sum(day_use_feed_man) AS day_use_feed_man,sum(day_use_water_auto) AS day_use_water_auto,sum(day_use_water_man) AS day_use_water_man ,his_date FROM t_hzfgw_node_status_his WHERE addr in ( SELECT device_addr FROM t_device WHERE houseid=%s AND device_type='HZFGW') AND his_date='%s' ", housid, today)
					dt, err = db.GetOne(sql)
					if err != nil {
						g.Log().Line().Error(err)
					} else {
						if dt != nil {
							list[k]["TodayFeed"] = dt.Map()
						}

					}
				}
				res["data"] = list
				res["count"] = len(list)
			}
		} else {
			res["code"] = -1
			res["msg"] = "您没有该操作权限"
		}
	}

	r.Response.WriteJson(res)
	r.ExitAll()
}
